import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  ImageBackground,
  Linking
} from 'react-native';
import {
  iconUserCoffee,
  iconUserGray,
  defaultman,
  iconDriver,
  iconSettingBlack,
  iconServiceBlack,
  iconLockBlack
} from '@/images';
import { msg, _, AsyncStorage, cache } from '@/common';
import { isAndroid, px2dp, mainBgColorLightGray } from '@/styles';
import userApi from '@/api/user';
import baseConfig from '@/config/baseConfig';
import { getAgreementByArray } from '@/common/agreement-version';
import RowItem from '../../../components/SimpleRowItem';

const { fileUrl, terminalCode } = baseConfig;

/**
 * @author kanglang
 * @description 车主端-我的/个人中心
 * @createDate 2020/8/25
 */
export default class User extends React.Component {
  static navigationOptions = () => ({
    title: '我的',
    tabBarIcon: ({ focused }) => (
      <Image source={focused ? iconUserCoffee : iconUserGray} style={{ width: 24, height: 24 }} />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      avatarId: '',
      name: '',
      serviceNumber: '',
      agreementList: []
    };
  }

  componentDidMount() {
    userApi.getUserInfo().then((res) => {
      if (res.success && res.data) {
        if (res.data.avatarId) {
          this.setState({
            avatarId: res.data.avatarId
          });
        }
        this.setState({
          name: res.data.nickName
        });
      }
    });
    // 货物运输协议
    getAgreementByArray(
      [{ appCode: terminalCode, code: 'logiticsAgreement', }],
      (data) => {
        this.setState({ agreementList: data });
      },
    );
    AsyncStorage.getItem(cache.SERVICE_NUMBER).then((res) => {
      this.setState({ serviceNumber: res });
    });
  }

  render() {
    const { avatarId, name, serviceNumber, agreementList } = this.state;
    return (
      <SafeAreaView style={styles.safeViewStyle}>
        <View style={styles.container}>
          <TouchableOpacity
            style={styles.settingWrap}
            onPress={() => this.goToSetting()}
          >
            <Image style={styles.settingImg} source={iconSettingBlack} />
          </TouchableOpacity>
          <ImageBackground
            style={styles.bgStyle}
            source={require('@/images/wl/chezhu_head_bg.png')}
            resizeMode='contain'
          >
            {
              avatarId ?
                <Image
                  style={styles.shipperAvartar}
                  source={{ uri: fileUrl + avatarId }}
                /> :
                <Image
                  style={styles.shipperAvartar}
                  source={defaultman}
                />
            }
            <Text style={styles.shipperName}>{name}</Text>
          </ImageBackground>
          <View style={styles.boxWrap}>
            {/* <View style={styles.certWrap}>
              <Text style={styles.shipperName}>{name}</Text>
              <View style={styles.certFlag}>
                <Image style={styles.certIcon} source={iconCaveatGreen} />
                <Text style={styles.certTip}>已认证</Text>
              </View>
            </View> */}
            <View style={styles.rowLine} />
            <RowItem
              style={styles.rowStyle}
              leftStyle={styles.pl0}
              rightStyle={styles.mr0}
              title='我的车辆'
              icon={require('../../../images/icons/icon_history.png')}
              onPress={this.myTruck}
            />
            <RowItem
              style={styles.rowStyle}
              leftStyle={styles.pl0}
              rightStyle={styles.mr0}
              title='我的司机'
              icon={iconDriver}
              onPress={this.myDriver}
            />
            {agreementList && agreementList.map((item => {
              if (!item || JSON.stringify(item) === '{}') return;
              return <RowItem
                style={styles.rowStyle}
                leftStyle={{ paddingLeft: 0 }}
                rightStyle={{ marginRight: 0 }}
                title={item.title}
                icon={require('../../../images/icons/icon_protocol.png')}
                onPress={() => this.wlProtocal(item)}
                renderSegment={false}
              />;
            }))}

          </View>
          <View style={styles.rowLine} />
          {/* <RowItem
            style={styles.rowStyle}
            leftStyle={styles.pl0}
            rightStyle={styles.mr0}
            title='油卡订单'
            icon={iconDriver}
            onPress={this.tOrder}
          /> */}
          <RowItem
            style={styles.rowStyle}
            leftStyle={styles.pl0}
            rightStyle={styles.mr0}
            title='账号安全'
            icon={iconLockBlack}
            onPress={this.goToAccountCenter}
          />
          <RowItem
            style={styles.rowStyle}
            leftStyle={styles.pl0}
            rightStyle={styles.mr0}
            title='客服热线'
            icon={iconServiceBlack}
            onPress={this.call}
            titleRight={serviceNumber}
            renderSegment={false}
          />
        </View>

      </SafeAreaView>
    );
  }

  goToAccountCenter = () => {
    msg.emit('router: goToNext', {
      routeName: 'AccountCenter',
    });
  };

  call = () => {
    const { phone } = this.state;
    if (!phone) return msg.emit('app:tip', { text: '联系电话无效' });
    const url = `tel:${phone}`;
    Linking.canOpenURL(url)
      .then((supported) => {
        if (!supported) {
          msg.emit('app:tip', { text: `您的设备不支持该功能，请手动拨打${phone}` });
          return;
        }
        return Linking.openURL(url);
      })
      .catch((err) => {
        msg.emit('app:tip', { text: err });
      });
  }

  goToSetting = () => {
    msg.emit('router: goToNext', {
      routeName: 'Setting',
    });
  };

  myTruck = () => {
    msg.emit('router: goToNext', {
      routeName: 'CarOwnerTruckList',
      routerFrom: 'CarOwnerUser'
    });
  }

  tOrder = () => {
    msg.emit('router: goToNext', {
      routeName: 'Order',
      toOrder: 2,
    });
  }

  myDriver = () => {
    msg.emit('router: goToNext', {
      routeName: 'MyDrive',
    });
  }

  wlProtocal = (item) => {
    msg.emit('router: goToNext', {
      routeName: 'CustAgreement',
      title: item.title,
      content: item.content
    });
  }
}

const styles = StyleSheet.create({
  safeViewStyle: {
    backgroundColor: '#fff',
  },
  container: {
    height: '100%',
    width: '100%',
    backgroundColor: '#fff',
  },
  bgStyle: {
    width: '100%',
    height: px2dp(312),
    paddingTop: px2dp(88),
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerStyle: {
    backgroundColor: 'rgba(0,0,0,0)',
    borderColor: 'rgba(0,0,0,0)',
    ..._.ifIphoneX({ top: 10 }, { top: 0 }),
  },
  backImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginLeft: isAndroid ? 0 : px2dp(34),
  },
  RowItemStyle: {
    paddingLeft: 0
  },
  shipperAvartar: {
    width: px2dp(135),
    height: px2dp(135),
    borderRadius: px2dp(135) * 2,
    marginLeft: px2dp(16) * 2,
    borderColor: '#F5F5F5',
    borderWidth: px2dp(13),
    // marginBottom: px2dp(30),
  },
  boxWrap: {
    // paddingTop: px2dp(12) * 2,
    // paddingBottom: px2dp(12) * 2
  },
  certWrap: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  shipperName: {
    color: '#343332',
    fontSize: px2dp(21) * 2,
    marginLeft: px2dp(30),
    // marginBottom: px2dp(66)
  },
  certFlag: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(12) * 2,
    backgroundColor: '#E9F8E9',
    paddingLeft: px2dp(8) * 2,
    paddingTop: px2dp(5),
    paddingRight: px2dp(8) * 2,
    paddingBottom: px2dp(5),
    borderRadius: px2dp(14) * 2
  },
  certIcon: {
    width: px2dp(11) * 2,
    height: px2dp(11) * 2
  },
  certTip: {
    color: '#2CBD26',
    fontSize: px2dp(11) * 2,
    marginLeft: px2dp(4) * 2
  },
  pl0: {
    paddingLeft: 0
  },
  mr0: {
    marginRight: 0,
    marginTop: px2dp(-1)
  },
  mt40: {
    marginTop: 40,
  },
  settingWrap: {
    width: px2dp(110),
    height: px2dp(88),
    right: px2dp(0),
    top: px2dp(0),
    position: 'absolute',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 10
  },
  settingImg: {
    width: px2dp(46),
    height: px2dp(46),
  },
  rowLine: {
    height: px2dp(20),
    backgroundColor: mainBgColorLightGray
  },
  rowStyle: {
    paddingHorizontal: px2dp(32)
  }
});
